import time
import datetime
# import numpy as np
import io
import matplotlib.pyplot as plt
from PIL import Image
import cv2
import os
import datetime
import numpy as np

import time
import multiprocessing as mp
from predict34 import class_predict34
from materialLevelDetect import serverToClientMsg
import struct
import socket


class material_level:
    def __init__(self):
        super(material_level, self).__init__()
        self.user_name, self.user_pwd = "admin", "@qwertyuiop159"
        self.camera_ip_l = ["192.168.10.140"] 
        self.camera_ip = "192.168.10.140"

        # 创建结构体对象并随机赋值
        self.msg = serverToClientMsg()
        self.msg.header = struct.pack('BB', 255, 7)
        self.msg.myData = struct.pack('BBBB', 7, 0, 0, 0)
        self.msg.setKind = [1, 1, 1, 1, 1]                 #各料库号
        self.msg.setBarn = [0 for _ in range(5)]    
        self.msg.kindSurplus = [4 for _ in range(5)]    #对应料库物料剩余量
        self.msg.setChooseMission = 0
        self.HOST = '192.168.8.41'
        self.PORT = 8888
        # self.connect()

    def connect(self):
        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            self.s.connect((self.HOST, self.PORT))
            self.flag = True
            print("connect_sucecss")
        except BaseException as e:
            self.flag = False
            print("connect_fail")

    def send_info(self):
        data = self.msg.pack()
        self.s.sendall(data)
        print(f'Sent {len(data)} bytes: {data}')

    def mul_camera(self,self_channel,current_num):
        class_pre34 = class_predict34()
        class_pre34.load_weight()
        cap = cv2.VideoCapture(
    "rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % (self.user_name, self.user_pwd, self.camera_ip, self_channel))
        while True:
            frame = cap.read()[1]
            frame = cv2.resize(frame, (640, 480))
            # file_object = io.BytesIO(frame)
            # basename = '/media/nvidia/0e55e00d-e578-494d-8fca-279b1d6aceaf/WheelLoaderProgram_ws/yunnan_kunming/dataset_2-3'
            # filename = f'{basename}/{self.channel}/frames_{str(datetime.datetime.now().strftime("%Y%m%d-%H%M%S%f"))}.jpg'
            # with open(filename, 'wb+') as f:
            #     f.write(frame)
            cv2.imshow("camera", frame)
            
            time.sleep(1)
            predict_result = class_pre34.predict34(frame)
            print("current_channel:",self_channel,"predict_result:",predict_result)
            self.msg.setKind[current_num - 1] = current_num
            self.msg.kindSurplus[current_num - 1] = int(predict_result)*2500
            # self.msg.setBarn[0] = current_num % 2
            print(self.msg.setBarn[0])
            print(time.time() - t1)
            if(time.time() - t1 > 3):
                t1 = time.time()

                try:
                    self.send_info()
                except BaseException as e:
                    print(e)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break 
        cap.release()
        cv2.destroyAllWindows()

if "__main__"==__name__:
    material_detect = material_level()
    channels = [3,5,7]
    nums = [1,2,3]
    pool = mp.Pool(3)
    results = []
    for cpu,num in zip(channels,nums):
        result = pool.apply_async(material_detect.camer_mul,args=(cpu,num))
        results.append(result)
    results = [r for r in results]
    pool.close()
    pool.join()
 